package com.example.music.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.music.R
import com.example.music.model.PlayList

class PlaylistAdapter : RecyclerView.Adapter<PlaylistAdapter.PlaylistViewHolder>() {
    private var playlists: List<PlayList> = emptyList()
    private var onItemClickListener: ((PlayList, Int, List<PlayList>) -> Unit)? = null

    fun submitList(newList: List<PlayList>) {
        playlists = newList
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(listener: (PlayList, Int, List<PlayList>) -> Unit) {
        onItemClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_playlist, parent, false)
        return PlaylistViewHolder(view)
    }

    override fun onBindViewHolder(holder: PlaylistViewHolder, position: Int) {
        holder.bind(playlists[position]) {
            onItemClickListener?.invoke(it, position, playlists)
        }
    }

    override fun getItemCount() = playlists.size

    class PlaylistViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val coverImage: ImageView = itemView.findViewById(R.id.playlistCover)
        private val nameText: TextView = itemView.findViewById(R.id.playlistName)
        private val artistText: TextView = itemView.findViewById(R.id.songCount)

        fun bind(playlist: PlayList, onClick: (PlayList) -> Unit) {
            nameText.text = playlist.name
            playlist.artist?.let {
                artistText.visibility = View.VISIBLE
                artistText.text = it
            } ?: run {
                artistText.visibility = View.GONE
            }
            
            Glide.with(itemView.context)
                .load(playlist.coverUrl)
                .placeholder(R.drawable.default_music_cover)
                .error(R.drawable.default_music_cover)
                .into(coverImage)

            itemView.setOnClickListener {
                onClick(playlist)
            }
        }
    }
} 